package com.st.vmall.util;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;

import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;

public class UploadUtil {
	
	/**
	 * 支持MultipartFile的文件上传
	 */
	public static String saveFile(MultipartFile file, HttpServletRequest request, String path) {
		
		if(file.getSize() == 0) {
			return null;
		}
		
		FileOutputStream fos = null;
		
		try {
			InputStream in = file.getInputStream();
			
			//文件存放的路径
			path = request.getServletContext().getRealPath(path);
			//随机的文件名
			String fileName = UUID.randomUUID().toString();
			//文件的后缀名，有些情况下没有后缀名
			if(file.getOriginalFilename().lastIndexOf(".") >= 0) {
				String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
				//文件名组合
				fileName += suffix;
			}
			
			//写到硬盘上
			fos = new FileOutputStream(path + "/" + fileName);
			
			IOUtils.copy(in, fos);
			
			return fileName;
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(fos != null) fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return null;
		
	}

	public static String saveFile(HttpServletRequest request,String name,String path) {

		FileOutputStream fos = null;
		
		try {
			//获取图片
			Part part = request.getPart(name);
			
			//字节输入流
			InputStream is = part.getInputStream();
			
			//获取文件夹路径
			path = request.getServletContext().getRealPath(path);
			
			//处理文件名
			String fileName = UUID.randomUUID().toString();
			
			//文件的后缀名
			String suffix = part.getSubmittedFileName().substring(part.getSubmittedFileName().indexOf("."));
			
			//文件名组合
			fileName += suffix;
			
			//写到硬盘上
			fos = new FileOutputStream(path + "/" + fileName);
			
			byte[] buff = new byte[1024];
			while(true) {
				int length = is.read(buff);
				if(length < 0) {
					break;
				}
				fos.write(buff, 0, length);
			}
			fos.flush();
			return fileName;
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ServletException e) {
			e.printStackTrace();
		} finally {
			try {
				if(fos != null) fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return null;
		
	}
	
}
